package org.sg20.labelpropagation.lpaiter;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

public class LpaIterDriver {
    /**
     * @param epoch 执行到第几轮
     * @param fsName 文件系统(HDFS or Local)
     * @param graphFile 链接文件(图文件)
     * @param labelNum 标签数量
     * @param initDotsFile   初始标签文件
     * @param outPath 输出路径
     */
    public  static  String run(int epoch,String fsName,String graphFile,int labelNum,int propagateNum,String initDotsFile, String outPath) throws IOException, InterruptedException, ClassNotFoundException{
        Configuration conf = new Configuration();
//        conf.set("fs.defaultFS",fsName);
        conf.setInt("label-num",labelNum);
        conf.setInt("propagate-num",propagateNum);
        FileSystem fs=FileSystem.get(conf);
        if(fs.exists(new Path(outPath)))
            fs.delete(new Path(outPath), true);

        Job job = Job.getInstance(conf);
        job.setJobName("LpaIter"+epoch);
        job.setInputFormatClass(KeyValueTextInputFormat.class);
        job.addCacheFile(new Path(initDotsFile).toUri());

        // 2 关联本Driver程序的jar
        job.setJarByClass(LpaIterDriver.class);

        // 3 关联Mapper和Reducer的jar
        job.setMapperClass(LpaIterMapper.class);  //和center共用一个mapper
        job.setReducerClass(LpaIterReducer.class);


        // 4 设置Mapper输出的kv类型
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(Text.class);

        // 5 设置最终输出kv类型
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);

        // 6 设置输入和输出路径
        FileInputFormat.setInputPaths(job, new Path(graphFile));
        FileOutputFormat.setOutputPath(job, new Path(outPath));

        // 7 提交job
        job.waitForCompletion(true);
        //return DigestUtils.md5Hex(fs.open(new Path(outPath+"/part-r-00000")));
        return  null;
    }

    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
        run(1,args[0],args[1],Integer.parseInt(args[2]),Integer.parseInt(args[3]),args[4],args[5]);
    }
}
